const titleElements = document.querySelectorAll(
  "#juejin > div.book-read-view > section > div.book-summary > div.book-summary-inner > div.book-directory-comp.beautify-scrollbar-warp.book-directory.is-buyer.bought > div.section-list > a > div.center > div.main-line > div.title > span"
)
const titleList = Array.from(titleElements).map((v, i) => `${i + 1} ${v.textContent}`)

const sectionElements = document.querySelectorAll(
  "#juejin > div.book-read-view > section > div.book-summary > div.book-summary-inner > div.book-directory-comp.beautify-scrollbar-warp.book-directory.is-buyer.bought > div.section-list > a"
)
const sectionList = Array.from(sectionElements)

const getHTML = (type = "view") => {
  const html = document.querySelector(
    "#juejin > div.book-read-view > section > div.book-content > div > div.book-body.transition--next > div > div > div > div.article-content > div"
  )
  const options = {
    juejin: {
      head: "",
      tail: "",
    },
    view: {
      head: "<body style='padding: 20px; width: 700px; margin-left: 25%; box-shadow: 0 0 10px #ccc;'>",
      tail: "</body>",
    },
  }
  if (html) {
    return options[type].head + html.outerHTML + options[type].tail
  }
  return ""
}

const transfer2Blob = (dataString, downloadName) => {
  let blob = new Blob([dataString])
  let url = window.URL.createObjectURL(blob)
  let a = document.createElement("a")
  document.body.appendChild(a)
  a.download = downloadName
  a.href = url
  a.click()
  document.body.removeChild(a)
}

const down = (link, wait, downloadName) => {
  return new Promise((resolve, reject) => {
    link.click()
    setTimeout(() => {
      const html = getHTML()
      if (html) {
        transfer2Blob(html, downloadName)
        resolve()
      } else {
        down(link, 0, downloadName)
      }
    }, wait)
  })
}
const interval = 3000
let p = Promise.resolve()
sectionList.forEach((v, i) => {
  p = p.then(
    () =>
      new Promise(async (resolve, reject) => {
        let res = await down(v, interval, titleList[i] + ".html")
        resolve(res)
      })
  )
})
